package com.xio.cloud.controller;

import cn.hutool.core.collection.CollUtil;
import com.xio.cloud.domain.CommonResult;
import com.xio.cloud.domain.Payment;
import com.xio.cloud.loadBalanced.IMyRoundRobinRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @Author: xio
 * @Description: 订单控制层
 * @Date: 2020/9/24 16:11
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    private static final String PAYMENT_URL = "http://cloud-payment-server";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private IMyRoundRobinRule myRoundRobinRule;

    @GetMapping("/save")
    public CommonResult save(Payment payment){
        log.info("- - - in order save");
        return restTemplate.postForObject(PAYMENT_URL+"/payment/save", payment, CommonResult.class);
    }

    @GetMapping("/get/{id}")
    public CommonResult get(@PathVariable("id") Long id){
        log.info("- - - in order get");
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id, CommonResult.class);
    }

    @GetMapping("/getForEntity/{id}")
    public CommonResult getForEntity(@PathVariable("id") Long id){
        log.info("- - - in order getForEntity");
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id, CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        }else{
            return CommonResult.fail();
        }
    }

    @GetMapping("/payment/lb")
    public String getPaymentLb(){
        List<ServiceInstance> instanceList = discoveryClient.getInstances("cloud-payment-server");
        if (CollUtil.isEmpty(instanceList)) {
            return null;
        }
        ServiceInstance service = myRoundRobinRule.instances(instanceList);
        URI uri = service.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }

    @GetMapping("/payment/zipkin")
    public String zipkin(){
        log.info("- - - in order payment zipkin");
        return restTemplate.getForObject("http://localhost:8001"+"/payment/zipkin", String.class);
    }
}
